package morenoapp.components.common.model;

import java.util.HashSet;
import java.util.Set;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import morenoapp.MorenoApp;
import morenoapp.components.common.model.wrap.QuestionValueWrapper;
import morenoapp.model.data.MorenoModelFace;
import morenoapp.model.listeners.MorenoModelAdapter;
import morenoapp.model.listeners.MorenoModelListener;

/**
 *
 * @author dmitry.mamonov
 */
public class QuestrionsComboBoxModel implements ComboBoxModel{
    MorenoModelFace model = MorenoApp.getModel();
    QuestionValueWrapper selected = null;
    Set<ListDataListener> listeners = new HashSet<ListDataListener>();

    MorenoModelListener modelListener = new MorenoModelAdapter(){
        @Override
        public void onQuestionsListChanged() {
            int size = getSize();
            selected = null;
            for(ListDataListener lst:listeners){
                lst.contentsChanged(new ListDataEvent(QuestrionsComboBoxModel.this,
                    ListDataEvent.CONTENTS_CHANGED, 0, size));
            }
        }
    };

    @Override
    public void setSelectedItem(Object anItem) {
        selected = (QuestionValueWrapper) anItem;
    }

    @Override
    public Object getSelectedItem() {
        return selected;
    }

    @Override
    public int getSize() {
        return model.getQuestionsList().size();
    }

    @Override
    public Object getElementAt(int index) {
        return new QuestionValueWrapper(model.getQuestionsList().get(index));
    }

    @Override
    public void addListDataListener(ListDataListener l) {
        listeners.add(l);
        if (listeners.size()==1){
            model.addModelListener(modelListener);
        }
    }

    @Override
    public void removeListDataListener(ListDataListener l) {
        listeners.remove(l);
        if (listeners.isEmpty()==true){
            model.removeModelListener(modelListener);
        }
    }
}
